from rest_framework import serializers
import logging, datetime, json
from django.db.models import Q, F, Max
from geopy.distance import geodesic
from django_redis import get_redis_connection
import random, requests
from random import randint

from users.models import *
from vouchers.models import *
from businesses.models import *
from cashbonus.models import *
from merchants.models import *
from orders.models import *
from goods.models import *
from equity_mall.utils.sync_img_to_local import make_qrcode1, make_qrcode4
from equity_mall.utils.utils import random_str
from activities.models import *
from newyears.models import *
from equity_mall.utils.express_utils import KuaiDi100
from equity_mall.utils.utils import redis_scheme_token_wyh
from equity_mall.utils.qiniu_storage import pic_upload
from businesses.utils import cancel_group_order
from equity_mall.utils.synchronous_coupons_status import synchronous_wx_coupons_status
from orders.utils import schengle

logger = logging.getLogger('django')


class CustomerUserViceInfoModelSerializer(serializers.ModelSerializer):

    # is_psbc_card = serializers.SerializerMethodField(read_only=True)
    is_sign_in = serializers.SerializerMethodField(read_only=True)
    is_merchant = serializers.SerializerMethodField(read_only=True)
    avatar = serializers.SerializerMethodField(read_only=True)
    is_restrict = serializers.SerializerMethodField(read_only=True)
    benben = serializers.SerializerMethodField(read_only=True)
    is_share = serializers.SerializerMethodField(read_only=True)
    is_bounty = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomerUserVice
        fields = ('id', 'point', 'obtain_point', 'use_point', 'is_psbc_card', 'is_mobile', 'mobile', 'avatar', 'username', 'is_sign_in', 'is_agreement', 'is_merchant',
                  'is_auth', 'is_restrict', 'benben', 'is_share', 'is_bounty')

    def get_is_bounty(self, obj):
        return 1
        if obj.id in [3073523, 2707851, 615593]:
            return 1
        else:
            return 0

    def get_is_share(self, obj):
        customizeactivity_id = 126
        customizeactivity = CustomizeActivity.objects.filter(id=customizeactivity_id, available_end_time__gte=datetime.datetime.now(), activity_status=1).first()
        if customizeactivity:
            check_white = CustomizeActivityWhiteTable.objects.filter(mobile=obj.mobile, customizeactivity_id=customizeactivity_id).first()
            if check_white:
                return 1
            else:
                return 0
        else:
            return 0

    def get_benben(self, obj):
        customizeactivity_id = 115
        customizeactivity = CustomizeActivity.objects.filter(id=customizeactivity_id, available_end_time__gte=datetime.datetime.now()).first()
        if customizeactivity:
            benbenorder_set = CustomizeActivityBenBenOrder.objects.filter(customeruservice_id=obj.id, open_status=1, customizeactivityflipcards_id__isnull=True)
            for benben_order in benbenorder_set:
                date_now = benben_order.pay_time
                customizeactivity = CustomizeActivity.objects.get(id=customizeactivity_id)
                if date_now < customizeactivity.available_begin_time or date_now > customizeactivity.available_end_time:
                    benben_order.open_status = 5
                    benben_order.save()
                else:
                    total_draws = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity_id, customeruservice_id=obj.id, win_type=6).count()
                    if total_draws < 3:
                        next_month = (date_now.month % 12) + 1
                        if next_month == 1:
                            next_month_first_day = date_now.replace(day=1, month=next_month, year=date_now.year + 1)
                        else:
                            next_month_first_day = date_now.replace(day=1, month=next_month)
                        this_month = next_month_first_day - datetime.timedelta(days=1)
                        this_month_first_day = this_month.strftime('%Y-%m-01 00:00:00')
                        this_month_last_day = this_month.strftime('%Y-%m-%d 23:59:59')
                        month_draws = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity_id, customeruservice_id=obj.id, win_type=6, pay_time__gte=this_month_first_day, pay_time__lte=this_month_last_day).count()
                        if month_draws < 1:
                            check_customizeactivityrules_set = customizeactivity.customizeactivityrules_set.filter(Q(alidiscountcoupon__remain_number__gt=0) | Q(cashactivity__remain_amount__gt=0))
                            check_customizeactivityrules_id_list = []
                            for check_customizeactivityrules in check_customizeactivityrules_set:
                                if check_customizeactivityrules.is_limit_by_day == 1:
                                    day_draws = CustomizeActivityFlipCARDS.objects.filter(customizeactivityrules_id=check_customizeactivityrules.id, pay_time__gte=date_now.strftime('%Y-%m-%d 00:00:00'), pay_time__lte=date_now.strftime('%Y-%m-%d 23:59:59')).count()
                                    if day_draws < check_customizeactivityrules.limit_by_day_count:
                                        check_customizeactivityrules_id_list.append(check_customizeactivityrules.id)
                            if not check_customizeactivityrules_id_list:
                                identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                                instance_data = dict()
                                instance_data['identify'] = identify
                                instance_data['customeruservice_id'] = obj.id
                                instance_data['gears'] = 1
                                instance_data['customizeactivity_id'] = customizeactivity.id
                                instance_data['open_status'] = 1
                                instance_data['open_time'] = None
                                instance_data['pay_time'] = date_now
                                instance_data['is_free'] = 0
                                instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
                                benben_order.customizeactivityflipcards_id = instance.id
                                benben_order.save()
                            else:
                                customizeactivityrules_id = random.choices(check_customizeactivityrules_id_list, k=1)[0]
                                customizeactivityrules = CustomizeActivityRules.objects.get(id=customizeactivityrules_id)
                                identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                                instance_data = dict()
                                instance_data['identify'] = identify
                                instance_data['customeruservice_id'] = obj.id
                                instance_data['gears'] = 1
                                instance_data['customizeactivity_id'] = customizeactivity.id
                                instance_data['customizeactivityrules_id'] = customizeactivityrules.id
                                instance_data['pay_time'] = date_now
                                instance_data['is_free'] = 0
                                if customizeactivityrules.prize_type in [1, 2]:
                                    instance_data['alidiscountcoupon_id'] = customizeactivityrules.alidiscountcoupon_id
                                    instance_data['win_type'] = customizeactivityrules.prize_type
                                elif customizeactivityrules.prize_type in [3, 6]:
                                    instance_data['cashactivity_id'] = customizeactivityrules.cashactivity_id
                                    instance_data['win_type'] = customizeactivityrules.prize_type
                                elif customizeactivityrules.prize_type == 5:
                                    instance_data['point'] = customizeactivityrules.point
                                    instance_data['win_type'] = customizeactivityrules.prize_type
                                instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
                                benben_order.customizeactivityflipcards_id = instance.id
                                benben_order.save()
                                cashactivity = instance.cashactivity
                                cashactivityrule = CashActivityRule.objects.filter(cash_activity_id=cashactivity.id, is_delete=0).first()
                                amount = cashactivityrule.amount
                                activity_id = cashactivity.id
                                while True:
                                    activity = CashActivity.objects.get(id=activity_id)
                                    activity_origin_take_amount = activity.take_amount
                                    activity_origin_remain_amount = activity.remain_amount
                                    activity_new_take_amount = activity_origin_take_amount + amount
                                    activity_new_remain_amount = activity_origin_remain_amount - amount
                                    result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                                    if result == 0:
                                        continue
                                    break
                                date_now = datetime.datetime.now()
                                activity_data = {}
                                activity_data['amount'] = amount
                                activity_data['create_time'] = date_now
                                activity_data['cash_activity_id'] = activity.id
                                activity_data['level_id'] = instance.level_id
                                activity_data['state'] = 1
                                identify = random_str()
                                nonce_str = random_str()
                                activity_data['identify'] = identify
                                activity_data['nonce_str'] = nonce_str
                                activity_data['desc'] = activity.name
                                activity_data['partner_trade_no'] = f'{date_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % obj.id}'
                                activity_data['customeruservice_id'] = obj.id
                                activity_data['mobile'] = obj.mobile
                                activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
                                instance.cashactivitydata_id = activity_dat.id
                                instance.amount = amount
                                instance.save()
                        else:
                            identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                            instance_data = dict()
                            instance_data['identify'] = identify
                            instance_data['customeruservice_id'] = obj.id
                            instance_data['gears'] = 1
                            instance_data['customizeactivity_id'] = customizeactivity.id
                            instance_data['open_status'] = 1
                            instance_data['open_time'] = None
                            instance_data['pay_time'] = date_now
                            instance_data['is_free'] = 0
                            instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
                            benben_order.customizeactivityflipcards_id = instance.id
                            benben_order.save()
                    else:
                        identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                        instance_data = dict()
                        instance_data['identify'] = identify
                        instance_data['customeruservice_id'] = obj.id
                        instance_data['gears'] = 1
                        instance_data['customizeactivity_id'] = customizeactivity.id
                        instance_data['open_status'] = 1
                        instance_data['open_time'] = None
                        instance_data['pay_time'] = date_now
                        instance_data['is_free'] = 0
                        instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
                        benben_order.customizeactivityflipcards_id = instance.id
                        benben_order.save()
            customizeactivityflipcards = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity_id, customeruservice_id=obj.id)
            if customizeactivityflipcards:
                return customizeactivity.id
        return ''

    def get_is_restrict(self, obj):
        try:
            today = datetime.datetime.now() - datetime.timedelta(days=90)
            if obj.update_time and obj.update_time > today:
                return 0
            else:
                return 1
        except:
            return 1

    def get_avatar(self, obj):
        try:
            if obj.avatar:
                return obj.avatar
            else:
                return 'https://circle.sutpay.cn/header.png'
        except:
            return 'https://circle.sutpay.cn/header.png'

    def get_is_merchant(self, obj):
        try:
            check_merchant = MerchantBusinessQRCode.objects.filter(customeruservice_id=obj.id)
            if check_merchant:
                return 1
            else:
                return 0
        except:
            return 0

    def get_is_sign_in(self, obj):
        try:
            today = datetime.datetime.now()
            today_date = today.strftime('%Y-%m-%d')
            today_sign = get_sign_in_db_model(obj.id).objects.filter(customeruservice_id=obj.id, date=today_date).first()
            if today_sign:
                return 1
            else:
                return 0
        except:
            return 1

    # def get_is_psbc_card(self, obj):
    #     try:
    #         if obj.is_psbc_card == 0:
    #             check_activity = CustomizeActivity.objects.filter(activity_type=5, activity_status=1).first()
    #             if check_activity:
    #                 return 0
    #             else:
    #                 return 1
    #         else:
    #             return obj.is_psbc_card
    #     except:
    #         return 1


class CustomizeActivityRulesModelSerializer(serializers.ModelSerializer):

    prize_type_str = serializers.CharField(source='get_prize_type_display', read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityRules
        fields = ['id', 'prize_type', 'prize_type_str', 'activity_info', 'count']

    def get_activity_info(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['activity_id'] = ''
        data['rule'] = ''
        data['available_begin_time'] = ''
        data['available_end_time'] = ''
        data['max'] = ''
        data['remain'] = ''
        data['take'] = ''
        data['amount'] = ''
        try:
            prize_type = obj.prize_type
            if prize_type in [1, 2]:
                alidiscountcoupon = obj.alidiscountcoupon
                data['id'] = alidiscountcoupon.id
                data['activity_name'] = alidiscountcoupon.activity_name
                data['activity_id'] = alidiscountcoupon.template_id
                data['rule'] = alidiscountcoupon.floor_amount
                data['available_begin_time'] = alidiscountcoupon.publish_start_time.strftime("%Y-%m-%d %H:%M:%S")
                data['available_end_time'] = alidiscountcoupon.publish_end_time.strftime("%Y-%m-%d %H:%M:%S")
                data['max'] = alidiscountcoupon.max_number
                data['remain'] = alidiscountcoupon.remain_number
                data['take'] = alidiscountcoupon.send_count
                data['amount'] = alidiscountcoupon.amount
            else:
                cashactivity = obj.cashactivity
                cashactivityrule_set = cashactivity.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'¥{cashactivityrule.amount},'
                data['id'] = cashactivity.id
                data['activity_name'] = cashactivity.name
                data['activity_id'] = cashactivity.activity_id
                data['rule'] = result[:-1]
                data['available_begin_time'] = cashactivity.available_begin_time.strftime("%Y-%m-%d %H:%M:%S")
                data['available_end_time'] = cashactivity.available_end_time.strftime("%Y-%m-%d %H:%M:%S")
                data['max'] = cashactivity.max_amount
                data['remain'] = cashactivity.remain_amount
                data['take'] = cashactivity.take_amount
                data['amount'] = result
        except:
            pass
        return data


class CustomizeActivityModelSerializer(serializers.ModelSerializer):

    customizeactivityrules_set = serializers.SerializerMethodField(read_only=True)
    pay_rules = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivity
        fields = ('id', 'activity_name', 'activity_description', 'customizeactivityrules_set', 'pay_rules')

    def get_pay_rules(self, obj):
        try:
            customizeactivitypayrules = obj.customizeactivitypayrules
            data = {}
            data['total_count'] = customizeactivitypayrules.total_count
            data['amount'] = customizeactivitypayrules.amount
            data['draw_counts'] = customizeactivitypayrules.draw_counts
            data['limit_merchant_count_by_day'] = customizeactivitypayrules.limit_merchant_count_by_day
            return data
        except:
            return {}

    def get_customizeactivityrules_set(self, obj):
        try:
            customizeactivityrules_set = obj.customizeactivityrules_set.filter(Q(alidiscountcoupon__remain_number__gt=0) | Q(cashactivity__remain_amount__gt=0)).exclude(count=0)
            data = CustomizeActivityRulesModelSerializer(customizeactivityrules_set, many=True).data
            return data
        except:
            return {}


class CustomizeActivityRetrieveModelSerializer(serializers.ModelSerializer):

    customizeactivityrules_set = serializers.SerializerMethodField(read_only=True)
    join_activity = serializers.SerializerMethodField(read_only=True)
    pay_rules = serializers.SerializerMethodField(read_only=True)
    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = CustomizeActivity
        fields = ('id', 'activity_name', 'activity_description', 'customizeactivityrules_set', 'join_activity', 'pay_rules',
                  'available_begin_time', 'available_end_time')

    def get_pay_rules(self, obj):
        try:
            customizeactivitypayrules = obj.customizeactivitypayrules
            data = {}
            data['total_count'] = customizeactivitypayrules.total_count
            data['amount'] = customizeactivitypayrules.amount
            data['draw_counts'] = customizeactivitypayrules.draw_counts
            data['limit_merchant_count_by_day'] = customizeactivitypayrules.limit_merchant_count_by_day
            return data
        except:
            return {}

    def get_join_activity(self, obj):
        data = {}
        data['id'] = ''
        data['is_join'] = ''
        data['is_join_str'] = ''
        try:
            user = self.context.get('user', None)
            join_data = {}
            join_data['customeruservice_id'] = user.id
            join_data['customizeactivity_id'] = obj.id
            join_activity, create = JoinCustomizeActivity.objects.get_or_create(defaults=join_data, customeruservice_id=user.id, customizeactivity_id=obj.id)
            data['id'] = join_activity.id
            data['is_join'] = join_activity.is_join
            data['is_join_str'] = join_activity.get_is_join_display()
        except:
            pass
        return data

    def get_customizeactivityrules_set(self, obj):
        try:
            customizeactivityrules_set = obj.customizeactivityrules_set.filter(Q(alidiscountcoupon__remain_number__gt=0) | Q(cashactivity__remain_amount__gt=0)).exclude(count=0)
            data = CustomizeActivityRulesModelSerializer(customizeactivityrules_set, many=True).data
            return data
        except:
            return {}


class CustomizeActivityFlipCARDSModelSerializer(serializers.ModelSerializer):

    open_status_str = serializers.CharField(source='get_open_status_display', read_only=True)
    result = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityFlipCARDS
        fields = ['id', 'open_status', 'open_status_str', 'result', 'return_msg']

    def get_result(self, obj):
        data = {}
        if obj.open_status == 1:
            return {}
        if obj.win_type == 4:
            data['amount'] = ''
            data['msg'] = ''
            data['win_type'] = obj.win_type
            data['win_type_str'] = obj.get_win_type_display()
            data['activity_name'] = ''
            data['usetime_type'] = ''
            return data
        elif obj.win_type in [3, 6]:
            data['amount'] = obj.amount
            data['msg'] = ''
            data['win_type'] = obj.win_type
            data['win_type_str'] = obj.get_win_type_display()
            data['activity_name'] = obj.cashactivity.name
            data['usetime_type'] = ''
            return data
        else:
            alidiscountcoupon = obj.alidiscountcoupon
            channelcommonvoucher = alidiscountcoupon.alidiscountcouponchannelcommonvoucher
            data['amount'] = alidiscountcoupon.amount
            data['msg'] = alidiscountcoupon.floor_amount
            data['win_type'] = obj.win_type
            data['win_type_str'] = obj.get_win_type_display()
            data['activity_name'] = alidiscountcoupon.activity_name
            if channelcommonvoucher.usetime_type == 2:
                data['usetime_type'] = f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
            elif channelcommonvoucher.usetime_type == 3:
                data['usetime_type'] = f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
            else:
                data['usetime_type'] = f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
            return data


class BindCardOrderRetrieveModelSerializer(serializers.ModelSerializer):

    customizeactivity = serializers.SerializerMethodField(read_only=True)
    customizeactivityflipcards = serializers.SerializerMethodField(read_only=True)
    order_status_str = serializers.CharField(source='get_order_status_display', read_only=True)
    prize_status_str = serializers.CharField(source='get_prize_status_display', read_only=True)

    class Meta:
        model = BindCardOrder
        fields = ('id', 'customizeactivity', 'order_status', 'prize_status', 'order_status_str', 'prize_status_str', 'customizeactivityflipcards')

    def get_customizeactivity(self, obj):
        try:
            if obj.prize_status == 1:
                data = CustomizeActivityModelSerializer(obj.customizeactivity).data
                return data
            else:
                return {}
        except:
            return {}

    def get_customizeactivityflipcards(self, obj):
        try:
            if obj.prize_status not in [1, 6]:
                data = CustomizeActivityFlipCARDSModelSerializer(obj.customizeactivityflipcards).data
                return data
            else:
                return {}
        except:
            return {}


class JoinCustomizeActivityRetrieveModelSerializer(serializers.ModelSerializer):

    customizeactivity = serializers.SerializerMethodField(read_only=True)
    is_join_str = serializers.CharField(source='get_is_join_display', read_only=True)

    class Meta:
        model = JoinCustomizeActivity
        fields = ('id', 'customizeactivity', 'is_join', 'is_join_str')

    def get_customizeactivity(self, obj):
        try:
            data = CustomizeActivityModelSerializer(obj.customizeactivity).data
            return data
        except:
            return {}


class AliDiscountCouponInfoListModelSerializer(serializers.ModelSerializer):

    gmt_create = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_expired = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_use = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    floor_amount = serializers.SerializerMethodField(read_only=True)
    amount = serializers.SerializerMethodField(read_only=True)
    coupon_channel = serializers.SerializerMethodField(read_only=True)
    is_need_auth = serializers.SerializerMethodField(read_only=True)
    coupon_type = serializers.SerializerMethodField(read_only=True)
    activity_description = serializers.SerializerMethodField(read_only=True)
    coupon_type_str = serializers.SerializerMethodField(read_only=True)
    usetime_type = serializers.SerializerMethodField(read_only=True)
    available_merchants = serializers.SerializerMethodField(read_only=True)
    is_couponbag = serializers.SerializerMethodField(read_only=True)
    usage_scenario_str = serializers.SerializerMethodField(read_only=True)
    contentLink = serializers.SerializerMethodField(read_only=True)
    is_use_path = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponInfo
        fields = ['id', 'gmt_create', 'mobile', 'status', 'status_str', 'gmt_expired', 'activity_name',
                  'floor_amount', 'amount', 'alidiscountcoupon_id', 'coupon_channel', 'is_need_auth', 'voucher_id', 'coupon_type',
                  'activity_description', 'coupon_type_str', 'usetime_type', 'gmt_use', 'available_merchants', 'is_couponbag', 'usage_scenario_str',
                  'contentLink', 'is_use_path']

    def get_usage_scenario_str(self, obj):
        try:
            if obj.alidiscountcoupon.usage_scenario:
                return obj.alidiscountcoupon.get_usage_scenario_display()
            else:
                return '指定商户可用'
        except:
            return ''

    def get_is_couponbag(self, obj):
        try:
            check_detail = CustomizeActivityFlipCARDSDetail.objects.filter(alidiscountcouponinfo_id=obj.id)
            if check_detail:
                return 1
            else:
                return 0
        except:
            return 0

    def get_contentLink(self, obj):
        contentLink = {
            "path": '',
            "appid": '',
            "is_self": ''
        }
        try:
            if obj.status == 1 and obj.alidiscountcoupon.is_use_path == 1:
                contentLink['path'] = obj.alidiscountcoupon.use_path + f"?coupon_id={obj.voucher_id}"
                contentLink['appid'] = obj.alidiscountcoupon.use_appid
                contentLink['is_self'] = obj.alidiscountcoupon.is_self
        except:
            pass
        return contentLink

    def get_is_use_path(self, obj):
        try:
            if obj.status == 1 and obj.alidiscountcoupon.is_use_path == 1:
                return 1
            else:
                return 0
        except:
            return 0

    def get_available_merchants(self, obj):
        try:
            return obj.alidiscountcoupon.available_merchants
        except:
            return ''

    def get_usetime_type(self, obj):
        try:
            alidiscountcoupon = obj.alidiscountcoupon
            channelcommonvoucher = alidiscountcoupon.alidiscountcouponchannelcommonvoucher
            if channelcommonvoucher.usetime_type == 2:
                return f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
            elif channelcommonvoucher.usetime_type == 3:
                return f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
            else:
                return f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
        except:
            return ''

    def get_coupon_type(self, obj):
        try:
            return obj.alidiscountcoupon.coupon_type
        except:
            return ''

    def get_coupon_type_str(self, obj):
        try:
            return obj.alidiscountcoupon.get_coupon_type_display()
        except:
            return ''

    def get_activity_description(self, obj):
        try:
            return obj.alidiscountcoupon.activity_description
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.alidiscountcoupon.activity_name
        except:
            return ''

    def get_is_need_auth(self, obj):
        try:
            return obj.alidiscountcoupon.is_need_auth
        except:
            return 0

    def get_coupon_channel(self, obj):
        try:
            return obj.alidiscountcoupon.coupon_channel
        except:
            return ''

    def get_floor_amount(self, obj):
        try:
            return obj.alidiscountcoupon.floor_amount
        except:
            return ''

    def get_amount(self, obj):
        try:
            if obj.alidiscountcoupon.coupon_type != 6:
                return obj.alidiscountcoupon.amount
            else:
                return '单品券'
        except:
            return ''


class AliDiscountCouponInfoRetrieveModelSerializer(serializers.ModelSerializer):

    gmt_create = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_use = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_expired = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_undo = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    gmt_active = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    floor_amount = serializers.SerializerMethodField(read_only=True)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    companyuser_nickname = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    coupon_channel = serializers.SerializerMethodField(read_only=True)
    activity_description = serializers.SerializerMethodField(read_only=True)
    coupon_type = serializers.SerializerMethodField(read_only=True)
    coupon_type_str = serializers.SerializerMethodField(read_only=True)
    usetime_type = serializers.SerializerMethodField(read_only=True)
    available_merchants = serializers.SerializerMethodField(read_only=True)
    is_use_path = serializers.SerializerMethodField(read_only=True)
    contentLink = serializers.SerializerMethodField(read_only=True)
    amount = serializers.SerializerMethodField(read_only=True)
    usage_scenario_str = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCouponInfo
        fields = ['id', 'gmt_create', 'mobile', 'status', 'status_str', 'floor_amount', 'companyuser_nickname',
                  'activity_name', 'gmt_use', 'gmt_expired', 'gmt_undo', 'alidiscountcoupon_id', 'coupon_channel',
                  'activity_description', 'gmt_active', 'coupon_type', 'coupon_type_str', 'usetime_type', 'available_merchants',
                  'is_use_path', 'contentLink', 'amount', 'usage_scenario_str']

    def get_usage_scenario_str(self, obj):
        try:
            if obj.alidiscountcoupon.usage_scenario:
                return obj.alidiscountcoupon.get_usage_scenario_display()
            else:
                return '指定商户可用'
        except:
            return ''

    def get_contentLink(self, obj):
        contentLink = {
            "path": '',
            "appid": '',
            "is_self": ''
        }
        try:
            if obj.status == 1 and obj.alidiscountcoupon.is_use_path == 1:
                path = obj.alidiscountcoupon.use_path + f"?coupon_id={obj.voucher_id}"
                if obj.level_id:
                    path += f'&level_id={obj.level_id}'
                contentLink['path'] = path
                contentLink['appid'] = obj.alidiscountcoupon.use_appid
                contentLink['is_self'] = obj.alidiscountcoupon.is_self
        except:
            pass
        return contentLink

    def get_is_use_path(self, obj):
        try:
            if obj.status == 1 and obj.alidiscountcoupon.is_use_path == 1:
                return 1
            else:
                return 0
        except:
            return 0

    def get_available_merchants(self, obj):
        try:
            return obj.alidiscountcoupon.available_merchants
        except:
            return ''

    def get_usetime_type(self, obj):
        try:
            alidiscountcoupon = obj.alidiscountcoupon
            channelcommonvoucher = alidiscountcoupon.alidiscountcouponchannelcommonvoucher
            if channelcommonvoucher.usetime_type == 2:
                return f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
            elif channelcommonvoucher.usetime_type == 3:
                return f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
            else:
                return f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
        except:
            return ''

    def get_coupon_type(self, obj):
        try:
            return obj.alidiscountcoupon.coupon_type
        except:
            return ''

    def get_coupon_type_str(self, obj):
        try:
            return obj.alidiscountcoupon.get_coupon_type_display()
        except:
            return ''

    def get_floor_amount(self, obj):
        try:
            return obj.alidiscountcoupon.floor_amount
        except:
            return ''

    def get_activity_description(self, obj):
        try:
            return obj.alidiscountcoupon.activity_description
        except:
            return ''

    def get_coupon_channel(self, obj):
        try:
            return obj.alidiscountcoupon.coupon_channel
        except:
            return ''

    def get_activity_name(self, obj):
        try:
            return obj.alidiscountcoupon.activity_name
        except:
            return ''

    def get_companyuser_nickname(self, obj):
        try:
            return obj.companyuser.nickname
        except:
            return ''

    def get_amount(self, obj):
        try:
            if obj.alidiscountcoupon.coupon_type != 6:
                return obj.alidiscountcoupon.amount
            else:
                return '单品券'
        except:
            return ''


class CustomizeActivityLimitModelSerializer(serializers.ModelSerializer):

    available_begin_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    available_end_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    activity_status = serializers.SerializerMethodField(read_only=True)
    point = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivity
        fields = ['id', 'activity_name', 'activity_description', 'activity_type', 'available_begin_time', 'available_end_time', 'activity_status', 'point']

    def get_activity_status(self, obj):
        data = {}
        data['status'] = obj.activity_status
        date_now = datetime.datetime.now()
        week = date_now.weekday()
        if obj.activity_type == 6:
            pass
        else:
            customizeactivitylotteryrules = obj.customizeactivitylotteryrules
            start_enable_time = customizeactivitylotteryrules.start_enable_time.strftime(' %H:%M:%S')
            end_enable_time = customizeactivitylotteryrules.end_enable_time.strftime(' %H:%M:%S')
            publish_start_time = datetime.datetime.strptime(date_now.strftime('%Y-%m-%d') + start_enable_time, '%Y-%m-%d %H:%M:%S')
            publish_end_time = datetime.datetime.strptime(date_now.strftime('%Y-%m-%d') + end_enable_time, '%Y-%m-%d %H:%M:%S')
            if customizeactivitylotteryrules.activity_mode == 1:
                if publish_start_time <= date_now and publish_end_time >= date_now:
                    data['status'] = 1
                else:
                    data['status'] = 0
                data['time'] = f'每天{publish_start_time.strftime("%H:%M")}-{publish_end_time.strftime("%H:%M")}'
            else:
                if str(week+1) not in customizeactivitylotteryrules.week_days:
                    data['status'] = 0
                else:
                    if publish_start_time <= date_now and publish_end_time >= date_now:
                        data['status'] = 1
                    else:
                        data['status'] = 0
                week_days = customizeactivitylotteryrules.week_days
                week_days = week_days.replace('1', '周一').replace('2', '周二').replace('3', '周三').replace('4', '周四').replace('5', '周五').replace('6', '周六').replace('7', '周日')
                data['time'] = f'逢{week_days}{publish_start_time.strftime("%H:%M")}-{publish_end_time.strftime("%H:%M")}'
        return data

    def get_point(self, obj):
        try:
            customizeactivitylotteryrules = obj.customizeactivitylotteryrules
            return customizeactivitylotteryrules.point
        except:
            return '0'


class CustomizeActivityFlipCARDSRetrieveModelSerializer(serializers.ModelSerializer):

    open_status_str = serializers.CharField(source='get_open_status_display', read_only=True)
    result = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityFlipCARDS
        fields = ['id', 'open_status', 'open_status_str', 'result', 'return_msg']

    def get_result(self, obj):
        data = {}
        if obj.open_status == 1:
            return {}
        if obj.win_type == 4:
            data['amount'] = ''
            data['msg'] = ''
            data['win_type'] = obj.win_type
            data['win_type_str'] = obj.get_win_type_display()
            data['activity_name'] = ''
            return data
        elif obj.win_type in [3, 6]:
            data['amount'] = obj.amount
            data['msg'] = ''
            data['win_type'] = obj.win_type
            data['win_type_str'] = obj.get_win_type_display()
            data['activity_name'] = obj.cashactivity.name
            return data
        else:
            alidiscountcoupon = obj.alidiscountcoupon
            data['amount'] = alidiscountcoupon.amount
            data['msg'] = alidiscountcoupon.floor_amount
            data['win_type'] = obj.win_type
            data['win_type_str'] = obj.get_win_type_display()
            # data['name'] = alidiscountcoupon.activity_name
            data['activity_name'] = alidiscountcoupon.activity_name
            return data


class CustomizeActivityRulesListModelSerializer(serializers.ModelSerializer):

    prize_type_str = serializers.CharField(source='get_prize_type_display', read_only=True)
    activity_info = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityRules
        fields = ['id', 'prize_type', 'prize_type_str', 'activity_info']

    def get_activity_info(self, obj):
        data = {}
        data['id'] = ''
        data['activity_name'] = ''
        data['activity_id'] = ''
        data['rule'] = ''
        data['available_begin_time'] = ''
        data['available_end_time'] = ''
        data['amount'] = ''
        try:
            prize_type = obj.prize_type
            if prize_type in [1, 2]:
                alidiscountcoupon = obj.alidiscountcoupon
                data['id'] = alidiscountcoupon.id
                data['activity_name'] = alidiscountcoupon.activity_name
                data['activity_id'] = alidiscountcoupon.template_id
                data['rule'] = alidiscountcoupon.floor_amount
                data['available_begin_time'] = alidiscountcoupon.publish_start_time.strftime("%Y-%m-%d %H:%M:%S")
                data['available_end_time'] = alidiscountcoupon.publish_end_time.strftime("%Y-%m-%d %H:%M:%S")
                data['amount'] = alidiscountcoupon.amount
            elif prize_type in [3, 6]:
                cashactivity = obj.cashactivity
                cashactivityrule_set = cashactivity.cashactivityrule_set.filter(is_delete=0).order_by('amount')
                result = ''
                for cashactivityrule in cashactivityrule_set:
                    result += f'¥{cashactivityrule.amount},'
                data['id'] = cashactivity.id
                data['activity_name'] = cashactivity.name
                data['activity_id'] = cashactivity.activity_id
                if obj.id in [751,752,753,754,755,756,757]:
                    data['rule'] = cashactivity.activity_description
                else:
                    data['rule'] = result[:-1]
                data['available_begin_time'] = cashactivity.available_begin_time.strftime("%Y-%m-%d %H:%M:%S")
                data['available_end_time'] = cashactivity.available_end_time.strftime("%Y-%m-%d %H:%M:%S")
                data['amount'] = result[:-1]
            elif prize_type == 5:
                data['amount'] = obj.point
        except:
            pass
        return data


class CustomizeActivityFlipCARDSListModelSerializer(serializers.ModelSerializer):

    open_status_str = serializers.CharField(source='get_open_status_display', read_only=True)
    result = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomizeActivityFlipCARDS
        fields = ['id', 'open_status', 'open_status_str', 'result', 'return_msg']

    def get_result(self, obj):
        data = {}
        if obj.open_status == 1:
            return {}
        if obj.win_type == 4:
            data['amount'] = ''
            data['msg'] = ''
            data['win_type'] = obj.win_type
            data['win_type_str'] = obj.get_win_type_display()
            data['activity_name'] = ''
            data['available_time'] = ''
            return data
        elif obj.win_type in [3, 6]:
            cashactivity = obj.cashactivity
            data['amount'] = obj.amount
            data['msg'] = ''
            data['win_type'] = obj.win_type
            data['win_type_str'] = obj.get_win_type_display()
            data['activity_name'] = obj.cashactivity.name
            data['available_time'] = f'{cashactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}-{cashactivity.available_begin_time.strftime("%Y.%m.%d %H:%M:%S")}'
            return data
        elif obj.win_type == 5:
            data['amount'] = obj.point
            data['msg'] = ''
            data['win_type'] = obj.win_type
            data['win_type_str'] = obj.get_win_type_display()
            data['activity_name'] = ''
            data['available_time'] = f''
            return data
        else:
            alidiscountcoupon = obj.alidiscountcoupon
            data['amount'] = alidiscountcoupon.amount
            data['msg'] = alidiscountcoupon.floor_amount
            data['win_type'] = obj.win_type
            data['win_type_str'] = obj.get_win_type_display()
            # data['name'] = alidiscountcoupon.activity_name
            data['activity_name'] = alidiscountcoupon.activity_name
            data['available_time'] = f'{alidiscountcoupon.publish_start_time.strftime("%Y.%m.%d %H:%M:%S")}-{alidiscountcoupon.publish_end_time.strftime("%Y.%m.%d %H:%M:%S")}'
            return data


class InviterCustomerUserViceListModelSerializer(serializers.ModelSerializer):

    inviter_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    point = serializers.SerializerMethodField(read_only=True)
    avatar = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CustomerUserVice
        fields = ['id', 'avatar', 'mobile', 'inviter_time', 'point']

    def get_point(self, obj):
        return '50'

    def get_avatar(self, obj):
        try:
            if obj.avatar:
                return obj.avatar
            else:
                return 'https://jinjian.sutpay.cn/image/wyh_img71.png'
        except:
            return 'https://jinjian.sutpay.cn/image/wyh_img71.png'


class MerchantListModelSerializer(serializers.ModelSerializer):

    distance = serializers.SerializerMethodField(read_only=True)
    business_qrcode = serializers.SerializerMethodField(read_only=True)
    open_work_time = serializers.DateTimeField(format="%H:%M", required=False)
    close_work_time = serializers.DateTimeField(format="%H:%M", required=False)
    is_coupon = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ['id', 'name', 'distance', 'store_address', 'longitude', 'latitude', 'store_header_copy', 'managermobile', 'store_logo_copy', 'short_name', 'business_qrcode',
                  'open_work_time', 'close_work_time', 'is_coupon']

    def get_is_coupon(self, obj):
        try:
            queryset = AliDiscountCoupon.objects.filter(alidiscountcouponmerchant__merchant_id=obj.id, coupon_status=1, coupon_way=2)
            if queryset:
                return 1
            else:
                return 0
        except:
            return 0

    def get_business_qrcode(self, obj):
        data = {}
        data['shop_id'] = ''
        data['status'] = 0
        try:
            business_qrcode = MerchantBusinessQRCode.objects.filter(merchant_id=obj.id).first()
            if business_qrcode:
                data['status'] = 1
                data['shop_id'] = business_qrcode.sn
        except:
            pass
        return data

    def get_distance(self, obj):
        longitude = self.context.get('longitude', None)
        latitude = self.context.get('latitude', None)
        if longitude and latitude:
            try:
                if obj.longitude and obj.latitude:
                    distance = geodesic((obj.latitude, obj.longitude), (latitude, longitude)).m
                    if distance > 1000:
                        return f'{round(distance/1000, 1)} km'
                    else:
                        return f'{int(distance)} m'
                else:
                    return ''
            except:
                return ''
        else:
            return ''


class MerchantRetrieveModelSerializer(serializers.ModelSerializer):

    open_work_time = serializers.DateTimeField(format="%H:%M", required=False)
    close_work_time = serializers.DateTimeField(format="%H:%M", required=False)
    merchantimage_set = serializers.SerializerMethodField(read_only=True)
    region = serializers.SerializerMethodField(read_only=True)
    merchant_home_qrcode = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ['id', 'name', 'short_name', 'managerName', 'merchant_desc', 'close_work_time', 'open_work_time', 'merchantimage_set', 'managermobile', 'store_address', 'longitude', 'latitude',
                  'region', 'merchant_home_qrcode']

    def get_merchantimage_set(self, obj):
        data = []
        try:
            # Merchant.objects.all()
            merchantimage_set = obj.merchantimage_set.all()
            for merchantimage in merchantimage_set:
                data.append(merchantimage.image.url)
        except:
            pass
        return data

    def get_region(self, obj):
        data = []
        try:
            if obj.prov_name:
                data.append(obj.prov_name)
                data.append(obj.city_name)
                data.append(obj.district_name)
        except:
            pass
        return data

    def get_merchant_home_qrcode(self, obj):
        try:
            if not obj.merchant_home_url:
                redis_conn = get_redis_connection("scheme")
                access_token = redis_conn.get('wyh_access_token')
                if access_token is None:
                    access_token = redis_scheme_token_wyh()
                else:
                    access_token = access_token.decode()
                url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                body = {
                    "page": "pages/sqm_active_store/sqm_active_store",
                    "scene": f"id={obj.id}",
                    "is_hyaline": True
                }
                response = requests.post(url=url, json=body)
                try:
                    if response.json()['errcode'] != 0:
                        access_token = redis_scheme_token_wyh()
                        url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                        response = requests.post(url=url, json=body)
                except:
                    pass
                reslut = response.content
                common_qrcode_url = pic_upload(reslut)
                merchant_home_url = f'https://api.sutpay.com/customer/merchant_home/?id={obj.id}'
                # merchant_home_qrcode = f'youhuiquanyi/{obj.wyfMerchantID}/merchant_home.png'
                # common_qrcode_url = make_qrcode(obj.wyfMerchantID, merchant_home_url, merchant_home_qrcode)
                obj.merchant_home_qrcode = common_qrcode_url
                obj.merchant_home_url = merchant_home_url
                obj.save()
                return f'https://circle.sutpay.cn/{common_qrcode_url}'
            else:
                return obj.merchant_home_qrcode.url
        except:
            return ''


class LevelModelSerializer(serializers.ModelSerializer):

    distance = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Level
        fields = ['id', 'name', 'longitude', 'latitude', 'address', 'distance', 'telephone', 'city_id', 'work_time']

    def get_distance(self, obj):
        longitude = self.context.get('longitude', None)
        latitude = self.context.get('latitude', None)
        if longitude and latitude:
            try:
                distance = geodesic((obj.latitude, obj.longitude), (latitude, longitude)).m
                if distance > 1000:
                    return f'{round(distance/1000, 1)}km'
                else:
                    return f'{int(distance)}m'
            except:
                return ''
        else:
            return ''


class OrderGoodsSerializer(serializers.ModelSerializer):

    default_image = serializers.SerializerMethodField(read_only=True)
    name = serializers.SerializerMethodField(read_only=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderGoods
        fields = ('id', 'default_image', 'count', 'price', 'name', 'merchant_name', 'goods_id', 'is_commented')

    def get_default_image(self, obj):
        try:
            return obj.goods.default_image.url
        except Exception as e:
            logger.error(e)
            return ''

    def get_name(self, obj):
        try:
            return obj.goods.name
        except Exception as e:
            logger.error(e)
            return ''

    def get_merchant_name(self, obj):
        try:
            return obj.goods.merchant.name
        except Exception as e:
            logger.error(e)
            return ''


class OrderInfoListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    # state_str = serializers.CharField(source='get_state_display', read_only=True)
    order_type_str = serializers.CharField(source='get_order_type_display', read_only=True)
    ordergoods_set = OrderGoodsSerializer(many=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)
    state_str = serializers.SerializerMethodField(read_only=True)
    order_species_str = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderInfo
        fields = ['id', 'create_time', 'order_id', 'state', 'state_str', 'ordergoods_set', 'total_price', 'merchant_name', 'order_type',
                  'order_type_str', 'order_species_str', 'order_species']

    def get_order_species_str(self, obj):
        try:
            if obj.order_species == 1:
                return '邮米'
            else:
                return '普通'
        except:
            return '普通'

    def get_state_str(self, obj):
        try:
            if obj.state == 9:
                return '发货中'
            else:
                return obj.get_state_display()
        except:
            return ''

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except Exception as e:
            logger.error(e)
            return ''


class GoodsCouponsModelSerializer(serializers.ModelSerializer):

    status_str = serializers.CharField(source='get_status_display', read_only=True)
    coupons_qrcode = serializers.SerializerMethodField(read_only=True)
    validity_time = serializers.SerializerMethodField(read_only=True)
    coupons_id_off = serializers.SerializerMethodField(read_only=True)
    service_name = serializers.SerializerMethodField(read_only=True)
    use_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = GoodsCoupons
        fields = ['id', 'validity_time', 'status_str', 'status', 'coupons_id', 'coupons_qrcode', 'use_time', 'coupons_id_off', 'service_name']

    def get_service_name(self, obj):
        try:
            dict1 = {
                "5264": "全套精洗（全车型）",
                "5221": "臭氧杀菌（不含洗车）",
                "4080": "汽车桑拿-空调清洗",
                "5058": "抛光打蜡（全车型）",
                "5261": "内饰清洗（全车型）",
            }
            schengle_coupons = OrderSchengleCoupons.objects.filter(couponId=obj.coupons_id).first()
            if schengle_coupons:
                return dict1[schengle_coupons.serviceId]
            else:
                return ''
        except:
            return ''

    def get_coupons_id_off(self, obj):
        try:
            coupons_id = obj.coupons_id
            return f'{coupons_id[:4]}****{coupons_id[-3:]}'
        except:
            return ''

    def get_validity_time(self, obj):
        try:
            if obj.order.order_type == 7:
                return (obj.validity_time + datetime.timedelta(days=29)).strftime("%Y-%m-%d %H:%M:%S")
            elif obj.order.order_type == 3:
                return obj.validity_time.strftime("%Y-%m-%d %H:%M:%S")
            else:
                if obj.goods_id in [1008211, 1008210, 1008212, 1008213, 10199146]:
                    if obj.status == 1:
                        if obj.validity_time < datetime.datetime.now():
                            obj.status = 3
                            obj.save()
                    return obj.validity_time.strftime("%Y-%m-%d %H:%M:%S")
                else:
                    return ''
        except:
            return ''

    def get_coupons_qrcode(self, obj):
        try:
            instance = GoodsCoupons.objects.get(id=obj.id)
            if not instance.coupons_qrcode:
                identify = random_str()
                coupon_qrcode = f'youhuiquanyi/goodscoupon/goodscoupon_{instance.goods_id}/{identify}.png'
                if obj.order.level:
                    coupon_qrcode_url = make_qrcode1(identify, f'https://qrcode.sutpay.com/manager/coupon/?sn={obj.coupons_id}', coupon_qrcode)
                else:
                    coupon_qrcode_url = make_qrcode1(identify, f'https://qrcode.sutpay.com/merchant/coupon/?sn={obj.coupons_id}', coupon_qrcode)
                instance.coupons_qrcode = coupon_qrcode
                instance.save()
                instance = GoodsCoupons.objects.get(id=obj.id)
            return instance.coupons_qrcode.url
        except Exception as e:
            return ''


class VoucherDetailModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = VoucherDetail
        fields = ['id', 'amount', 'name', 'voucherId']


class OrderFundTransSerializer(serializers.ModelSerializer):

    status_str = serializers.SerializerMethodField(read_only=True)
    trans_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_reason = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderFundTrans
        fields = ['id', 'pay_fund_order_id', 'exchange_amount', 'name', 'status', 'status_str',
                  'trans_date', 'status_reason', 'identity']

    def get_status_str(self, obj):
        try:
            if obj.status == 2:
                return '交易成功'
            else:
                return f'交易失败'
        except:
            return ''

    def get_status_reason(self, obj):
        try:
            if obj.status == 2:
                return '请使用上述账户登录支付宝APP，点击【我的】-【余额】-【余额变动明细】查询。'
            else:
                return f'{obj.sub_msg}。具体请联系客户经理修改收款信息.'
        except:
            return ''


class OrderAddressModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = OrderAddress
        fields = ['id', 'receiver', 'place', 'mobile', 'province', 'city', 'district']


class ExpressPlanModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = ExpressPlan
        fields = ('id', 'create_time', 'remark')


class ExpressModelSerializer(serializers.ModelSerializer):

    deliverystatus_str = serializers.CharField(source='get_deliverystatus_display', read_only=True)
    deliverystatus = serializers.SerializerMethodField(read_only=True)
    express_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expressplan_set = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Express
        fields = ('id', 'deliverystatus', 'deliverystatus_str', 'express_number', 'express_name', 'create_time', 'expressplan_set')

    def get_deliverystatus(self, obj):
        try:
            if obj.deliverystatus in [0, 1, 5, 2, 6]:
                redis_conn = get_redis_connection("express_number")
                express_number_flag = redis_conn.get("express_number_%s" % obj.express_number)
                if not express_number_flag:
                    redis_conn.setex('express_number_%s' % obj.express_number, 21600, 1)
                    order = ExpressOrderRelevance.objects.filter(express_id=obj.id).first()
                    phone = OrderAddress.objects.filter(order_id=order.order_id).first()
                    if phone:
                        result = KuaiDi100().track(obj.express_type.express_type, obj.express_number, phone.mobile[-4:])
                    else:
                        result = KuaiDi100().track(obj.express_type.express_type, obj.express_number)
                    if result['status'] == '200':
                        obj.deliverystatus = result['state']
                        obj.save()
                        if obj.deliverystatus == 3:
                            try:
                                order = obj.order
                                user = order.user
                            except:
                                pass
                        for i in result['data']:
                            plan_data = {}
                            plan_data['express_id'] = obj.id
                            plan_data['create_time'] = i['time']
                            plan_data['remark'] = i['context']
                            ExpressPlan.objects.get_or_create(defaults=plan_data, create_time=i['time'], express_id=obj.id)
                        if str(obj.deliverystatus) == "3":
                            try:
                                sign_time = ExpressPlan.objects.filter(express_id=obj.id).aggregate(Max('create_time'))['create_time__max']
                                obj.sign_time = sign_time
                                obj.save()
                            except:
                                pass
                    else:
                        obj.deliverystatus = 9
                        obj.save()
                        ExpressPlan.objects.create(remark=result['message'], create_time=datetime.datetime.now(), express_id=obj.id)
            return obj.deliverystatus
        except:
            return obj.deliverystatus

    def get_expressplan_set(self, obj):
        try:
            expressplan_set = obj.expressplan_set.all().order_by('-create_time')
            return ExpressPlanModelSerializer(expressplan_set, many=True).data
        except:
            return []

    def get_express_name(self, obj):
        try:
            return obj.express_type.express_type_name
        except:
            return ''


class AfterSaleApplicationFormListModelSerializer(serializers.ModelSerializer):

    form_status_str = serializers.CharField(source='get_form_status_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    refund_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    img_array = serializers.SerializerMethodField(read_only=True)
    reason = serializers.SerializerMethodField(read_only=True)
    order = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AfterSaleApplicationForm
        fields = ['id', 'form_status', 'form_status_str', 'create_time', 'description', 'refund_money', 'return_msg', 'refund_time', 'reason', 'img_array',
                  'application_num', 'order']

    def get_order(self, obj):
        data = {}
        data['id'] = ''
        data['merchant_name'] = ''
        data['order_id'] = ''
        data['default_image'] = ''
        data['goods_name'] = ''
        try:
            order = obj.order
            order_goods = OrderGoods.objects.filter(order_id=order.id).first()
            goods = order_goods.goods
            data['id'] = order.id
            data['merchant_name'] = order.merchant.name
            data['order_id'] = order.orderNum
            data['default_image'] = goods.default_image.url
            data['goods_name'] = goods.name
        finally:
            return data

    def get_reason(self, obj):
        try:
            return obj.reason.name
        except:
            return ''

    def get_img_array(self, obj):
        data = []
        try:
            queryset = AfterSaleApplicationFormImg.objects.filter(applicationform_id=obj.id)
            for query in queryset:
                data.append(query.img.url)
        except:
            pass
        return data


class AfterSaleApplicationFormRetrieveModelSerializer(serializers.ModelSerializer):

    form_status_str = serializers.CharField(source='get_form_status_display', read_only=True)
    reason_type_str = serializers.CharField(source='get_reason_type_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    refund_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expired_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    img_array = serializers.SerializerMethodField(read_only=True)
    reason = serializers.SerializerMethodField(read_only=True)
    order = serializers.SerializerMethodField(read_only=True)
    address = serializers.SerializerMethodField(read_only=True)
    number = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AfterSaleApplicationForm
        fields = ['id', 'form_status', 'form_status_str', 'create_time', 'description', 'refund_money', 'return_msg', 'refund_time', 'reason', 'img_array',
                  'application_num', 'order', 'address', 'reason_type', 'reason_type_str', 'number', 'expired_time']

    def get_number(self, obj):
        return 1

    def get_order(self, obj):
        data = {}
        data['id'] = ''
        data['merchant_name'] = ''
        data['default_image'] = ''
        data['total_price'] = ''
        data['goods_name'] = ''
        try:
            order = obj.order
            order_goods = OrderGoods.objects.filter(order_id=order.id).first()
            data['id'] = order.id
            data['merchant_name'] = order.merchant.name
            data['default_image'] = order_goods.goods.default_image.url
            data['total_price'] = order.total_price
            data['goods_name'] = order_goods.goods.name
        finally:
            return data

    def get_reason(self, obj):
        try:
            return obj.reason.name
        except:
            return ''

    def get_img_array(self, obj):
        data = []
        try:
            queryset = AfterSaleApplicationFormImg.objects.filter(applicationform_id=obj.id)
            for query in queryset:
                data.append(query.img.url)
        except:
            pass
        return data

    def get_address(self, obj):
        data = {}
        data['receiver'] = ''
        data['place'] = ''
        data['mobile'] = ''
        try:
            merchant = obj.order.merchant
            data['receiver'] = merchant.managerName
            data['place'] = merchant.store_address
            data['mobile'] = merchant.managermobile
        finally:
            return data


class OrderInfoRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    cancel_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    # state_str = serializers.CharField(source='get_state_display', read_only=True)
    ordergoods_set = OrderGoodsSerializer(many=True)
    customer_user = serializers.SerializerMethodField(read_only=True)
    goodscoupons_set = serializers.SerializerMethodField(read_only=True)
    # goodscoupons_set = GoodsCouponsModelSerializer(many=True)
    voucherdetail_set = VoucherDetailModelSerializer(many=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)
    discount_amount = serializers.SerializerMethodField(read_only=True)
    realpay_amount = serializers.SerializerMethodField(read_only=True)
    order_type_str = serializers.CharField(source='get_order_type_display', read_only=True)
    orderfundtrans_set = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)
    total_point = serializers.SerializerMethodField(read_only=True)
    orderaddress = serializers.SerializerMethodField(read_only=True)
    express_info = serializers.SerializerMethodField(read_only=True)
    state_str = serializers.SerializerMethodField(read_only=True)
    after_sale = serializers.SerializerMethodField(read_only=True)
    is_aftersale = serializers.SerializerMethodField(read_only=True)
    aftersale_choices = serializers.SerializerMethodField(read_only=True)
    group_data = serializers.SerializerMethodField(read_only=True)
    expired_time = serializers.SerializerMethodField(read_only=True)
    is_sd_order = serializers.SerializerMethodField(read_only=True)
    order_species_str = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderInfo
        fields = ['id', 'create_time', 'order_id', 'state', 'state_str', 'ordergoods_set', 'total_price', 'customer_user', 'goodscoupons_set', 'voucherdetail_set',
                  'merchant_name', 'payment_time', 'cancel_time', 'realpay_amount', 'discount_amount', 'order_type_str', 'order_type',
                  'orderfundtrans_set', 'level', 'total_point', 'orderaddress', 'express_info', 'after_sale', 'is_aftersale', 'aftersale_choices',
                  'merchant_id', 'group_data', 'expired_time', 'is_sd_order', 'order_species', 'order_species_str']

    def get_order_species_str(self, obj):
        try:
            if obj.order_species == 1:
                return '邮米'
            else:
                return '普通'
        except:
            return '普通'

    def get_is_sd_order(self, obj):
        if obj.merchant_id in [1827370, 1166424]:
            return 1
        else:
            return 0

    def get_goodscoupons_set(self, obj):
        try:
            if obj.order_type == 3:
                sd_order = OrderSchengle.objects.filter(order_id=obj.id, order_state__in=[4, 2], end_time__gte=datetime.datetime.now()).first()
                if sd_order:
                    result = schengle.query_order({"outTradeNo": sd_order.outTradeNo})
                    if result['resultCode'] == 'success':
                        couponInfoList = result['data']['couponDetailList']
                        use_time = None
                        for couponInfo in couponInfoList:
                            couponId = couponInfo['couponId']
                            if couponInfo['status'] == 5:
                                use_time = couponInfo['useTime']
                                OrderSchengleCoupons.objects.filter(couponId=couponId).update(coupon_state=5,
                                                                                              useTime=couponInfo['useTime'],
                                                                                              useShopCode=couponInfo['useShopCode'],
                                                                                              useShopName=couponInfo['useShopName'],
                                                                                              useCityCode=couponInfo['useCityCode'],
                                                                                              useCityName=couponInfo['useCityName'],
                                                                                              )
                                GoodsCoupons.objects.filter(coupons_id=couponId).update(use_time=couponInfo['useTime'],status=2)
                                sd_order.order_state = 4
                                sd_order.save()
                            elif couponInfo['status'] == 6:
                                use_time = couponInfo['useTime']
                                OrderSchengleCoupons.objects.filter(couponId=couponId).update(coupon_state=6)
                                GoodsCoupons.objects.filter(coupons_id=couponId).update(status=3)
                        check_coupons = OrderSchengleCoupons.objects.filter(order_id=obj.id, coupon_state=1)
                        if not check_coupons:
                            sd_order.order_state = 5
                            sd_order.save()
                            obj.state = 3
                            obj.use_time = use_time
                            obj.save()
            if obj.state not in [15, 8]:
                goodscoupons_set = obj.goodscoupons_set.all()
                return GoodsCouponsModelSerializer(goodscoupons_set, many=True).data
            return []
        except:
            return []

    def get_expired_time(self, obj):
        try:
            expired_time = obj.create_time + datetime.timedelta(minutes=15)
            return expired_time.strftime("%Y-%m-%d %H:%M:%S")
        except:
            return ''

    def get_group_data(self, obj):
        data = {}
        if obj.state in [13]:
            return data
        data['group_status'] = ''
        data['expired_time'] = ''
        data['account'] = ''
        data['people_list'] = []
        data['count'] = ''
        data['qrcode'] = ''
        data['share_pic'] = ''
        data['goods'] = {}
        data['is_self'] = 0
        try:
            group = obj.group
            if group:
                if group.group_status == 1:
                    cancel_group_order(group)
                if obj.state == 8:
                    data['group_status'] = 3
                else:
                    data['group_status'] = group.group_status if group.group_status != 0 else 4
                data['expired_time'] = group.expired_time.strftime("%Y-%m-%d %H:%M:%S")
                data['account'] = group.account
                goods = group.goods
                data['goods'] = {
                    "id": goods.id,
                    "price": goods.price,
                    "default_image": goods.default_image.url,
                    "name": goods.name,
                    "group_price": goods.group_price,
                }
                order_set = OrderInfo.objects.filter(group_id=obj.group_id, state__in=[15, 2, 8, 1, 3])
                count = group.group_order_num - len(order_set)
                data['count'] = count
                for order in order_set:
                    customeruservice = order.customeruservice
                    if customeruservice.avatar:
                        data['people_list'].append(customeruservice.avatar)
                    else:
                        data['people_list'].append('https://suppliera.postwork.cn/static/img/header.f38b3311.png')
                for i in range(count):
                    data['people_list'].append('https://jinjian.sutpay.cn/image/wyh_img128.png')
                if not group.qrcode:
                    redis_conn = get_redis_connection("scheme")
                    access_token = redis_conn.get('wyh_access_token')
                    if access_token is None:
                        access_token = redis_scheme_token_wyh()
                    else:
                        access_token = access_token.decode()
                    url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                    body = {
                        "page": "pages/pro_detail_group/pro_detail_group",
                        "scene": f"id={goods.id}&account={group.account}",
                        "is_hyaline": True,
                    }
                    response = requests.post(url=url, json=body)
                    try:
                        if response.json()['errcode'] != 0:
                            access_token = redis_scheme_token_wyh()
                            url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                            response = requests.post(url=url, json=body)
                    except:
                        pass
                    reslut = response.content
                    market_code = pic_upload(reslut)
                    # merchant_home_qrcode = f'youhuiquanyi/{obj.wyfMerchantID}/merchant_home.png'
                    # common_qrcode_url = make_qrcode(obj.wyfMerchantID, merchant_home_url, merchant_home_qrcode)
                    group.qrcode = market_code
                    group.save()
                    data['qrcode'] = f'https://circle.sutpay.cn/{market_code}'
                else:
                    data['qrcode'] = group.qrcode.url
                data['share_pic'] = group.share_pic.url
        except:
            pass
        return data

    def get_is_aftersale(self, obj):
        try:
            if obj.order_type == 5 and obj.state not in [5, 8, 10, 1, 6]:
                if obj.payment_time <= (datetime.datetime.now() + datetime.timedelta(days=-30)):
                    return 0
                return 1
            else:
                return 0
        except:
            return 0

    def get_aftersale_choices(self, obj):
        data = []
        if obj.state == 9:
            data.append({
                'reason_type': 1,
                'name': '仅退款',
                'status': 1
            })
            data.append({
                'reason_type': 2,
                'name': '退货退款',
                'status': 0
            })
            data.append({
                'reason_type': 3,
                'name': '换货',
                'status': 0
            })
        else:
            data.append({
                'reason_type': 1,
                'name': '仅退款',
                'status': 1
            })
            data.append({
                'reason_type': 2,
                'name': '退货退款',
                'status': 1
            })
            data.append({
                'reason_type': 3,
                'name': '换货',
                'status': 1
            })
        return data

    def get_after_sale(self, obj):
        try:
            after_sale = AfterSaleApplicationForm.objects.exclude(form_status=4).filter(order_id=obj.id).last()
            if after_sale:
                return AfterSaleApplicationFormListModelSerializer(after_sale).data
            else:
                return {}
        except:
            return {}

    def get_state_str(self, obj):
        try:
            if obj.state == 9:
                return '发货中'
            elif obj.state == 15:
                group = obj.group
                check_group_order = OrderInfo.objects.filter(state=15, group_id=group.id)
                if len(check_group_order) >= group.group_order_num:
                    check_group_order.update(state=2)
                    group.group_status = 2
                    group.save()
                return obj.get_state_display()
            else:
                return obj.get_state_display()
        except:
            return ''

    def get_express_info(self, obj):
        try:
            express_id_list = ExpressOrderRelevance.objects.filter(order_id=obj.id).values_list('express_id', flat=True)
            express_set = Express.objects.filter(id__in=list(express_id_list))
            return ExpressModelSerializer(express_set, many=True).data
        except:
            return []

    def get_orderaddress(self, obj):
        try:
            orderaddress = obj.orderaddress
            if orderaddress:
                return OrderAddressModelSerializer(orderaddress).data
            else:
                return {}
        except:
            return {}

    def get_total_point(self, obj):
        try:
            return obj.total_point / 100
        except:
            return 0

    def get_orderfundtrans_set(self, obj):
        try:
            orderfundtrans_set = obj.orderfundtrans_set.exclude(status=1)
            return OrderFundTransSerializer(orderfundtrans_set, many=True).data
        except:
            return []

    def get_level(self, obj):
        data = {}
        data['name'] = ''
        data['longitude'] = ''
        data['latitude'] = ''
        data['address'] = ''
        data['telephone'] = ''
        data['city_id'] = ''
        data['work_time'] = ''
        data['id'] = ''
        try:
            level = obj.level
            if level:
                if obj.order_type in [1, 4, 7]:
                    data['name'] = level.name
                data['longitude'] = level.longitude
                data['latitude'] = level.latitude
                data['address'] = level.address
                data['telephone'] = level.telephone
                data['city_id'] = level.city_id
                data['work_time'] = level.work_time
                data['id'] = level.id
                data['merchant_id'] = ''
            else:
                merchant = obj.merchant
                data['name'] = merchant.short_name
                data['longitude'] = merchant.longitude
                data['latitude'] = merchant.latitude
                data['address'] = merchant.store_address
                data['telephone'] = merchant.managermobile
                data['city_id'] = ''
                data['work_time'] = ''
                data['id'] = ''
                data['merchant_id'] = merchant.id
        except:
            pass
        return data

    def get_customer_user(self, obj):
        data = {}
        data['realname'] = ''
        data['mobile'] = ''
        try:
            customer_user = obj.customer_user
            if customer_user:
                data['mobile'] = customer_user.mobile
                data['realname'] = customer_user.realname
            else:
                customeruservice = obj.customeruservice
                data['mobile'] = customeruservice.mobile
                data['realname'] = customeruservice.realname
            return data
        except Exception as e:
            logger.error(e)
        return data

    def get_discount_amount(self, obj):
        try:
            if obj.state in [12, 2, 3, 9, 6, 8, 5, 14]:
                return str(Decimal(obj.total_price - obj.realpay_amount).quantize(Decimal('0.00')))
            elif obj.state == 1:
                return str(Decimal(obj.total_price - obj.payable_amount).quantize(Decimal('0.00')))
            else:
                return '0.00'
        except Exception as e:
            logger.error(e)
        return '0.00'

    def get_realpay_amount(self, obj):
        try:
            if obj.state == 1:
                return obj.payable_amount
            else:
                return obj.realpay_amount
        except Exception as e:
            logger.error(e)
        return '0.00'

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except Exception as e:
            logger.error(e)
            return ''


class ActivityDataListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    point = serializers.SerializerMethodField(read_only=True)
    remain_point = serializers.SerializerMethodField(read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)
    available_time = serializers.SerializerMethodField(read_only=True)
    amount = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ActivityData
        fields = ['id', 'create_time', 'state_str', 'state', 'point', 'activity_name', 'available_time', 'remain_point', 'amount']

    def get_point(self, obj):
        try:
            point = str(int(obj.point))
            if len(point) >= 3:
                return f'{point[:-2]},{point[-2:]}'
            else:
                return point
        except:
            return '0'

    def get_remain_point(self, obj):
        try:
            remain_point = str(int(obj.remain_point))
            if len(remain_point) >= 3:
                return f'{remain_point[:-2]},{remain_point[-2:]}'
            else:
                return remain_point
        except:
            return '0'

    def get_amount(self, obj):
        try:
            return obj.remain_point / Decimal('100')
        except:
            return '0'

    def get_activity_name(self, obj):
        try:
            return obj.activity.name
        except:
            return ''

    def get_available_time(self, obj):
        try:
            activity = obj.activity
            return f'{activity.available_end_time.strftime("%Y/%m/%d %H:%M:%S")}'
        except:
            return ''


class GoodsListModelSerializer(serializers.ModelSerializer):

    merchant_name = serializers.SerializerMethodField(read_only=True)
    stock = serializers.SerializerMethodField(read_only=True)
    order_type_str = serializers.CharField(source='get_order_type_display', read_only=True)
    ratio = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'price', 'merchant_name', 'sales', 'default_image', 'name', 'stock',
                  'order_type', 'order_type_str', 'market_price', 'ratio', 'group_price', 'is_group')

    def get_ratio(self, obj):
        try:
            sales = obj.sales
            stock = obj.remain_stock + obj.sales
            return int(sales / stock * 100)
        except:
            return ''

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''

    def get_stock(self, obj):
        level_id = self.context.get('level_id', None)
        if level_id:
            launchedgoods = LaunchedGoods.objects.filter(level_id=level_id, goods_id=obj.id).first()
            if launchedgoods:
                return launchedgoods.stock
            else:
                return 0
        else:
            return obj.remain_stock


class GoodsRetrieveModelSerializer(serializers.ModelSerializer):

    merchant_name = serializers.SerializerMethodField(read_only=True)
    goodsimage_set = serializers.SerializerMethodField(read_only=True)
    desc_detail = serializers.SerializerMethodField(read_only=True)
    stock = serializers.SerializerMethodField(read_only=True)
    order_type_str = serializers.CharField(source='get_order_type_display', read_only=True)
    market_code = serializers.SerializerMethodField(read_only=True)
    order_type_list = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'price', 'merchant_name', 'sales', 'default_image', 'goodsimage_set', 'desc_detail', 'name', 'market_price', 'stock',
                  'order_type', 'order_type_str', 'is_buymore', 'merchant_id', 'manufacturer', 'specifications', 'caption', 'market_code',
                  'is_group', 'group_price', 'group_order_num', 'order_type_list', 'desc_pack')

    def get_order_type_list(self, obj):
        data = []
        try:
            if obj.order_type == 1:
                launched_goods = LaunchedGoods.objects.filter(is_self=1, goods_id=obj.id, is_launched=1)
                if launched_goods:
                    data.append({"order_type_str": "商家门店自提", "order_type": 8})
                launched_goods = LaunchedGoods.objects.filter(is_self=0, goods_id=obj.id, is_launched=1)
                if launched_goods:
                    data.append({"order_type_str": "邮政网点自提", "order_type": 9})
            else:
                data.append({"order_type_str": obj.get_order_type_display(), "order_type": obj.order_type})
        except:
            pass
        return data

    def get_desc_detail(self, obj):
        try:
            return json.loads(obj.desc_detail)
        except:
            return obj.desc_detail

    def get_goodsimage_set(self, obj):
        data = []
        try:
            goodsimage_set = obj.goodsimage_set.all()
            for goodsimage in goodsimage_set:
                data.append(goodsimage.image.url)
        except:
            pass
        return data

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.short_name
        except:
            return ''

    def get_stock(self, obj):
        level_id = self.context.get('level_id', None)
        if level_id:
            launchedgoods = LaunchedGoods.objects.filter(level_id=level_id, goods_id=obj.id).first()
            if launchedgoods:
                return launchedgoods.stock
            else:
                return 0
        else:
            return obj.remain_stock

    def get_market_code(self, obj):
        try:
            if not obj.market_url:
                redis_conn = get_redis_connection("scheme")
                access_token = redis_conn.get('wyh_access_token')
                if access_token is None:
                    access_token = redis_scheme_token_wyh()
                else:
                    access_token = access_token.decode()
                url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                body = {
                    "page": "pages/pro_detail/pro_detail",
                    "scene": f"goods_id={obj.id}&level_id=",
                    "is_hyaline": True
                }
                response = requests.post(url=url, json=body)
                try:
                    if response.json()['errcode'] != 0:
                        access_token = redis_scheme_token_wyh()
                        url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}'
                        response = requests.post(url=url, json=body)
                except:
                    pass
                reslut = response.content
                market_code = pic_upload(reslut)
                market_url =f'https://qrcode.sutpay.com/business/market_goods/?goods_id={obj.id}&level_id='
                # merchant_home_qrcode = f'youhuiquanyi/{obj.wyfMerchantID}/merchant_home.png'
                # common_qrcode_url = make_qrcode(obj.wyfMerchantID, merchant_home_url, merchant_home_qrcode)
                obj.market_url = market_url
                obj.market_code = market_code
                obj.save()
                return f'https://circle.sutpay.cn/{market_code}'

                # market_url = f'https://qrcode.sutpay.com/business/market_goods/?goods_id={obj.id}&level_id='
                # market_code = make_qrcode1(obj.merchant.wyfMerchantID, market_url, None)
                # obj.market_url = market_url
                # obj.market_code = market_code
                # obj.save()
                # return f'https://circle.sutpay.cn/{market_code}'
            else:
                return obj.market_code.url
        except:
            return ''


class CashActivityDataListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    activity_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityData
        fields = ['id', 'create_time', 'state_str', 'state', 'amount', 'activity_name']

    def get_activity_name(self, obj):
        try:
            return obj.cash_activity.name
        except:
            return ''


class CashActivityDataRetrieveModelSerializer(serializers.ModelSerializer):

    activity_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CashActivityData
        fields = ['id', 'amount', 'activity_name', 'available_time']

    def get_activity_name(self, obj):
        try:
            return obj.activity.name
        except:
            return ''


class NewYearsShoppingFestivalElectListModelSerializer(serializers.ModelSerializer):

    available_begin_time = serializers.DateTimeField(format="%Y.%m.%d", required=False)
    available_end_time = serializers.DateTimeField(format="%Y.%m.%d", required=False)

    class Meta:
        model = NewYearsShoppingFestivalElect
        fields = ['id', 'available_begin_time', 'available_end_time', 'activity_description', 'activity_name']


class NewYearsShoppingFestivalElectProductListModelSerializer(serializers.ModelSerializer):

    rank = serializers.SerializerMethodField(read_only=True)
    is_vote = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = NewYearsShoppingFestivalElectProduct
        fields = ['id', 'product_title', 'default_image', 'rank', 'is_vote', 'product_intro', 'like_count']

    def get_is_vote(self, obj):
        try:
            user = self.context.get('user')
            today = datetime.datetime.today().strftime('%Y%m%d')
            identification = f'{today}{"%06d" % obj.id}{"%06d" % user.id}'
            check_like = NewYearsShoppingFestivalElectProductLike.objects.filter(identification=identification)
            if check_like:
                return 1
            else:
                return 0
        except:
            return 1

    def get_rank(self, obj):
        try:
            if obj.is_match == 1:
                queryset = list(NewYearsShoppingFestivalElectProduct.objects.filter(is_match=1).order_by('-like_count').values_list('id', flat=True))
                return queryset.index(obj.id) + 1
            else:
                return ''
        except:
            return 0


class NewYearsShoppingFestivalElectProductRetrieveModelSerializer(serializers.ModelSerializer):

    rank = serializers.SerializerMethodField(read_only=True)
    is_vote = serializers.SerializerMethodField(read_only=True)
    image_set = serializers.SerializerMethodField(read_only=True)
    product_qrcode = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = NewYearsShoppingFestivalElectProduct
        fields = ['id', 'product_title', 'default_image', 'rank', 'is_vote', 'product_intro', 'image_set', 'like_count', 'product_qrcode']

    def get_is_vote(self, obj):
        try:
            user = self.context.get('user')
            today = datetime.datetime.today().strftime('%Y%m%d')
            identification = f'{today}{"%06d" % obj.id}{"%06d" % user.id}'
            check_like = NewYearsShoppingFestivalElectProductLike.objects.filter(identification=identification)
            if check_like:
                return 1
            else:
                return 0
        except:
            return 1

    def get_rank(self, obj):
        try:
            if obj.is_match == 1:
                queryset = list(NewYearsShoppingFestivalElectProduct.objects.filter(is_match=1).order_by('-like_count').values_list('id', flat=True))
                return queryset.index(obj.id) + 1
            else:
                return ''
        except:
            return 0

    def get_image_set(self, obj):
        data = []
        try:
            image_set = obj.newyearsshoppingfestivalelectproductpic_set.all()
            for image in image_set:
                data.append(image.image.url)
        except:
            pass
        return data

    def get_product_qrcode(self, obj):
        try:
            if not obj.product_qrcode:
                product_url = f'https://qrcode.sutpay.com/business/elect_product/?product_id={obj.id}'
                product_qrcode = make_qrcode4(obj.id, product_url, None)
                obj.product_url = product_url
                obj.product_qrcode = product_qrcode
                obj.save()
                return f'https://circle.sutpay.cn/{product_qrcode}'
            else:
                return obj.product_qrcode.url
        except:
            return ''


class NewYearsShoppingFestivalElectProductLikeListModelSerializer(serializers.ModelSerializer):

    product_title = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = NewYearsShoppingFestivalElectProductLike
        fields = ['id', 'product_title', 'product_id', 'create_time']

    def get_product_title(self, obj):
        try:
            return obj.product.product_title
        except:
            return ''


class CustomerUserViceAddressModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = CustomerUserViceAddress
        fields = ['id', 'receiver', 'province', 'city', 'district', 'place', 'mobile', 'sex', 'is_default']


class AfterSaleReasonModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = AfterSaleReason
        fields = ['id', 'name']


class ExpressListModelSerializer(serializers.ModelSerializer):

    express_type = serializers.SerializerMethodField(read_only=True)
    express_type_logo = serializers.SerializerMethodField(read_only=True)
    address = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    sign_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    deliverystatus_str = serializers.CharField(source='get_deliverystatus_display', read_only=True)
    expressplan_set = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Express
        fields = ('id', 'express_type_id', 'express_type', 'express_type_logo', 'express_number', 'create_time', 'sign_time',
                  'deliverystatus', 'deliverystatus_str', 'address', 'expressplan_set')

    def get_expressplan_set(self, obj):
        try:
            expressplan_set = obj.expressplan_set.all().order_by('-create_time')
            return ExpressPlanModelSerializer(expressplan_set, many=True).data
        except:
            return []

    def get_address(self, obj):
        data = {}
        try:
            order = ExpressOrderRelevance.objects.filter(express_id=obj.id).first().order
            if obj.nature == 1:
                address = OrderAddress.objects.filter(order_id=order.id).first()
                data['receiver'] = address.receiver
                data['place'] = address.place
                data['mobile'] = address.mobile
            else:
                merchant = order.merchant
                data['receiver'] = merchant.managerName
                data['place'] = merchant.store_address
                data['mobile'] = merchant.managermobile
        except:
            pass
        return data

    def get_express_type(self, obj):
        try:
            return obj.express_type.express_type_name
        except:
            return ''

    def get_express_type_logo(self, obj):
        try:
            return obj.express_type.logo
        except:
            return ''


class ExpressRetrieveModelSerializer(serializers.ModelSerializer):

    express_type = serializers.SerializerMethodField(read_only=True)
    express_type_logo = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    sign_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    deliverystatus_str = serializers.CharField(source='get_deliverystatus_display', read_only=True)
    expressplan_set = serializers.SerializerMethodField(read_only=True)
    order_set = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Express
        fields = ('id', 'express_type_id', 'express_type', 'express_type_logo', 'express_number', 'create_time', 'sign_time',
                  'deliverystatus', 'deliverystatus_str', 'expressplan_set', 'order_set')

    def get_order_set(self, obj):
        try:
            order_id_list = obj.expressorderrelevance_set.all().values_list('order_id', flat=True)
            order_set = OrderInfo.objects.filter(id__in=list(order_id_list))
            return OrderInfoListModelSerializer(order_set, many=True).data
        except:
            return []

    def get_expressplan_set(self, obj):
        try:
            expressplan_set = obj.expressplan_set.all().order_by('-create_time')
            return ExpressPlanModelSerializer(expressplan_set, many=True).data
        except:
            return []

    def get_express_type(self, obj):
        try:
            return obj.express_type.express_type_name
        except:
            return ''

    def get_express_type_logo(self, obj):
        try:
            return obj.express_type.logo
        except:
            return ''


class ExpressTypeModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = ExpressType
        fields = ('id', 'express_type_name', 'logo')


class OrderGoodsCommentFileModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = OrderGoodsCommentFile
        fields = ('id', 'file', 'file_type')


class OrderGoodsListModelSerializer(serializers.ModelSerializer):

    default_image = serializers.SerializerMethodField(read_only=True)
    name = serializers.SerializerMethodField(read_only=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)
    ordergoodscommentfile_set = OrderGoodsCommentFileModelSerializer(many=True)
    comment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = OrderGoods
        fields = ('id', 'default_image', 'count', 'price', 'name', 'merchant_name', 'goods_id', 'is_commented', 'comment', 'ordergoodscommentfile_set',
                  'comment_time', 'is_anonymous', 'order_id')

    def get_default_image(self, obj):
        try:
            return obj.goods.default_image.url
        except Exception as e:
            logger.error(e)
            return ''

    def get_name(self, obj):
        try:
            return obj.goods.name
        except Exception as e:
            logger.error(e)
            return ''

    def get_merchant_name(self, obj):
        try:
            return obj.goods.merchant.name
        except Exception as e:
            logger.error(e)
            return ''


class OrderGoodsRetrieveModelSerializer(serializers.ModelSerializer):

    default_image = serializers.SerializerMethodField(read_only=True)
    name = serializers.SerializerMethodField(read_only=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)
    ordergoodscommentfile_set = OrderGoodsCommentFileModelSerializer(many=True)
    comment_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)

    class Meta:
        model = OrderGoods
        fields = ('id', 'default_image', 'count', 'price', 'name', 'merchant_name', 'goods_id', 'is_commented', 'comment', 'ordergoodscommentfile_set',
                  'comment_time', 'is_anonymous', 'order_id')

    def get_default_image(self, obj):
        try:
            return obj.goods.default_image.url
        except Exception as e:
            logger.error(e)
            return ''

    def get_name(self, obj):
        try:
            return obj.goods.name
        except Exception as e:
            logger.error(e)
            return ''

    def get_merchant_name(self, obj):
        try:
            return obj.goods.merchant.name
        except Exception as e:
            logger.error(e)
            return ''


class GoodsCommentModelSerializer(serializers.ModelSerializer):

    ordergoodscommentfile_set = OrderGoodsCommentFileModelSerializer(many=True)
    comment_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    username = serializers.SerializerMethodField(read_only=True)
    avatar = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderGoods
        fields = ('id', 'is_commented', 'comment', 'ordergoodscommentfile_set',
                  'comment_time', 'is_anonymous', 'avatar', 'username')

    def get_username(self, obj):
        try:
            if obj.is_anonymous == 1:
                return '匿名买家'
            else:
                return obj.order.customeruservice.username
        except:
            return '匿名买家'

    def get_avatar(self, obj):
        try:
            if obj.is_anonymous == 1:
                return 'https://jinjian.sutpay.cn/image/wyh_img101.png'
            else:
                return obj.order.customeruservice.avatar
        except:
            return 'https://jinjian.sutpay.cn/image/wyh_img101.png'


class ScoutTheStoreLeaderboardModelSerializer(serializers.ModelSerializer):

    creator = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ScoutTheStoreLeaderboard
        fields = ('city', 'merhant_name', 'likes', 'creator')

    def get_creator(self, obj):
        try:
            return json.loads(obj.creator.replace("'", '"'))
        except:
            return ['-']


class AliDiscountCouponModelSerializer(serializers.ModelSerializer):

    state = serializers.SerializerMethodField(read_only=True)
    publish_end_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    publish_start_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    coupon_type_str = serializers.CharField(source='get_coupon_type_display', read_only=True)
    usetime_type = serializers.SerializerMethodField(read_only=True)
    merchant_id = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AliDiscountCoupon
        fields = ['id', 'activity_name', 'amount', 'transaction_minimum', 'floor_amount', 'state', 'activity_description',
                  'publish_start_time', 'publish_end_time', 'coupon_type_str', 'coupon_channel', 'available_merchants', 'usetime_type',
                  'merchant_id']

    def get_merchant_id(self, obj):
        try:
            merchant = AliDiscountCouponMerchant.objects.filter(alidiscountcoupon_id=obj.id, merchant_id__isnull=False).first()
            return merchant.merchant_id
        except:
            return ''

    def get_usetime_type(self, obj):
        try:
            if obj.coupon_type in [2, 6, 8]:
                channelcommonvoucher = obj.alidiscountcouponchannelcommonvoucher
                if channelcommonvoucher.usetime_type == 2:
                    return f'固定使用时间{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d")}'
                elif channelcommonvoucher.usetime_type == 3:
                    return f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
                else:
                    return f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
            else:
                return ''
        except:
            return ''

    def get_state(self, obj):
        user = self.context.get('user', None)
        if not user:
            return 1
        else:
            try:
                query = AliDiscountCouponInfo.objects.filter(customeruservice_id=user.id, alidiscountcoupon_id=obj.id)
                if 1 in query.values_list('status', flat=True):
                    try:
                        id_list = query.filter(status=1).values_list('id', flat=True)
                        synchronous_wx_coupons_status(list(id_list))
                        query2 = AliDiscountCouponInfo.objects.filter(customeruservice_id=user.id, alidiscountcoupon_id=obj.id)
                        if 1 in query2.values_list('status', flat=True):
                            return 2
                        elif obj.max_number_by_user > query2.count():
                            if obj.remain_number <= 0:
                                return 3
                            return 1
                        else:
                            return 2
                    except:
                        pass
                    return 2
                elif obj.max_number_by_user > query.count():
                    if obj.remain_number <= 0:
                        return 3
                    return 1
                else:
                    return 2
            except:
                return 3

